package cdu.hjx.project.sys.handler;

import cdu.hjx.project.pojo.DictDetail;
import cdu.hjx.project.sys.service.DictDetailSerivce;
import cdu.hjx.project.utils.CommonResult;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@CrossOrigin
@RestController
@RequestMapping("/dicts")
public class DictDetailHandler {
    @Resource
    private DictDetailSerivce dictDetailService;

    /**
     * 添加字典详情
     * @param dictDetail 字典详情
     * @return CommonResult 统一返回类
     */
    @PostMapping("/add")
    public CommonResult addDictDetail(@RequestBody DictDetail dictDetail) {
        try {
            int i = dictDetailService.insertDictDetail(dictDetail);
            return i > 0 ? CommonResult.success(dictDetail) : CommonResult.error(500, "添加字典详情失败");
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResult.error(501, "系统异常,添加失败,请联系管理员.");
        }
    }

    /**
     * 查询字典详情
     * @param dtype 字典类型
     * @return CommonResult 统一返回类
     */
    @GetMapping("/{dtype}/{pn}/{size}")
    public CommonResult<PageInfo<DictDetail>> findDictDetail(
            @PathVariable("dtype") String dtype,
            @PathVariable("pn") int pn,
            @PathVariable("size") int size
    ) {
        try {
            PageHelper.startPage(pn, size);
            List<DictDetail> dictDetails = dictDetailService.findDictDetailByType(dtype);
            PageInfo<DictDetail> pageInfo = new PageInfo<>(dictDetails);
            return null != dictDetails ? CommonResult.success(pageInfo) : CommonResult.error(201, "请求成功,没有查询到字典详情数据.");
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResult.error(502, "系统异常,查询失败,请联系管理员.");
        }
    }

}